package com.dmall.graph.bfs;

import com.dmall.graph.Graph;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class CC {

    private Graph G;
    private int[] visited;
    private int cccount = 0;

    public CC(Graph G) {
        this.G = G;
        visited = new int[G.V()];
        for (int i = 0; i < G.V(); i++) {
            visited[i] = -1;
        }
        for (int i = 0; i < G.V(); i++) {
            if (visited[i] == -1) {
                bfs(i, cccount);
                cccount ++;
            }
        }
    }

    private void bfs(int v, int ccid) {
        Queue<Integer> queue = new LinkedList<>();
        visited[v] = ccid;
        queue.add(v);
        while (!queue.isEmpty()) {
            Integer cur = queue.remove();
            for (Integer w : G.adj(cur)) {
                if (visited[w] == -1) {
                    visited[w] = ccid;
                    queue.add(w);
                }
            }
        }
    }

    public int count() {
        return cccount;
    }

    public boolean isConnectedTo(int v, int w) {
        G.validateVertex(v);
        G.validateVertex(w);
        return visited[v] == visited[w];
    }

    public ArrayList<Integer>[] components() {
        ArrayList<Integer>[] res = new ArrayList[count()];
        for (int i = 0; i < count(); i++) {
            res[i] = new ArrayList<>();
        }
        for (int i = 0; i < G.V(); i++) {
            res[visited[i]].add(i);
        }
        return res;
    }

    public static void main(String[] args) {
        String filename = CC.class.getClassLoader().getResource("g.txt").getPath();
        Graph g = new Graph(filename);
        CC cc = new CC(g);
        System.out.println(cc.count());
        System.out.println(cc.isConnectedTo(0, 6));
        System.out.println(cc.isConnectedTo(0, 5));
        ArrayList<Integer>[] components = cc.components();
        for(int ccid = 0; ccid < components.length; ccid ++) {
            System.out.print(ccid + " : ");
            for(int w: components[ccid]) {
                System.out.print(w + " ");
            }
            System.out.println();
        }
    }
}
